import {
    checkPermission,
    ensureGroupAndPlayerExist,
    formatCurrency,
    getConfig,
    getGroupPlayerList,
    getPlayerData,
    storagePlayerData
} from "../function/function.js";
import fs from 'fs';
export class Rob extends plugin {
    constructor() {
        super({
            name: '[Sm]抢劫',
            dsc: '尝试抢劫其他玩家的金币',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/](抢劫|打劫)$/, fnc: 'rob' },
                { reg: /^[#\/]重置(抢劫|打劫)冷却$/, fnc: 'resetrob' }
            ]
        })
    }

    async rob(e) {
        try {
            if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
            const ID = [e.user_id, e.group_id];

            // 使用通用函数检查和初始化群组和玩家
            ensureGroupAndPlayerExist(ID[1], ID[0]);

            const userData = await getPlayerData(ID[1], ID[0]);
            const { currency, lastRobTime, master, bankBalance = 0 } = userData;

            // 计算抢劫者总财富(余额+银行存款)
            const robberTotalWealth = currency + bankBalance;

            const currentSecond = Math.floor(Date.now() / 1000);
            const config = getConfig();
            const robCooldown = config.rob.cooldown; // 从配置文件读取冷却时间

            if (!checkPermission(e) && currentSecond - (lastRobTime || 0) < robCooldown) {
                const remainingTime = robCooldown - (currentSecond - lastRobTime);
                return e.reply([`抢劫冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }

            // 获取群成员信息
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            // 判断是否指定打劫目标
            let targetId;
            if (e.at) {
                ensureGroupAndPlayerExist(ID[1], e.at);
                targetId = e.at;
            } else {
                // 随机选择一个目标
                const groupPlayerList = getGroupPlayerList(ID[1]);
                targetId = groupPlayerList[Math.floor(Math.random() * groupPlayerList.length)].replace('.json', '');
            }

            if (targetId === ID[0]) return e.reply(['你不能抢劫自己']);
            if (targetId === master) return e.reply(['你不能抢劫你的主人']);

            const targetData = await getPlayerData(ID[1], targetId);
            const { currency: targetCurrency, bankBalance: targetBankBalance = 0 } = targetData;

            // 计算目标总财富（余额+银行存款）
            const targetTotalWealth = targetCurrency + targetBankBalance;

            // 获取基础配置
            const baseSuccessRate = config.rob.successRate || 0.4; // 基础成功率
            const basePenalty = config.rob.penalty || 0.15;       // 基础惩罚比例

            const targetNickname = memberInfoList[targetId]?.nickname || '未知用户';
            const userNickname = memberInfoList[ID[0]]?.nickname || ID[0];

            // 计算财富差距系数 (正值表示目标比劫匪富有)
            // 现在使用总财富（余额+银行存款）计算差距
            let wealthGap = targetTotalWealth - robberTotalWealth;
            let wealthRatio = 0;
            
            if (wealthGap > 0) {
                // 目标比劫匪富有，增加成功率和抢劫金额
                wealthRatio = Math.min(wealthGap / Math.max(robberTotalWealth, 100), 10); // 限制最大比率为10
            } else {
                // 目标比劫匪穷，降低成功率和抢劫金额
                wealthRatio = Math.max(wealthGap / Math.max(targetTotalWealth, 100), -0.8); // 限制最小比率为-0.8
            }
            
            // 根据财富差距调整成功率 (±30%)
            const adjustedSuccessRate = baseSuccessRate + (wealthRatio * 0.03);
            const finalSuccessRate = Math.min(Math.max(adjustedSuccessRate, 0.1), 0.9); // 限制在10%-90%之间
            
            // 根据财富差距调整惩罚比例
            const adjustedPenalty = basePenalty - (wealthRatio * 0.01);
            const finalPenalty = Math.min(Math.max(adjustedPenalty, 0.05), 0.25); // 限制在5%-25%之间

            // 计算战力对比（如果可能）
            let powerFactor = 0;
            try {
                const fightModule = await import('./fight.js');
                const fightInstance = new fightModule.Fight();
                
                // 获取双方战力
                const robberPower = await fightInstance.calculatePower(ID[1], ID[0], userData);
                const targetPower = await fightInstance.calculatePower(ID[1], targetId, targetData);
                
                // 计算战力差距对成功率的影响 (±10%)
                powerFactor = (robberPower - targetPower) / Math.max(targetPower, 100);
                powerFactor = Math.min(Math.max(powerFactor, -0.1), 0.1);
            } catch (error) {
                logger.warn('无法加载战力模块，将不考虑战力因素');
            }

            // 将战力因素纳入最终成功率
            const finalRate = Math.min(Math.max(finalSuccessRate + powerFactor, 0.1), 0.9);
            
            // 输出详细调试信息
            logger.debug(`[抢劫系统] ${userNickname}(总财富:${robberTotalWealth}金币) -> ${targetNickname}(总财富:${targetTotalWealth}金币)`);
            logger.debug(`财富差距比: ${wealthRatio.toFixed(2)}, 调整后成功率: ${finalRate.toFixed(2)}, 惩罚率: ${finalPenalty.toFixed(2)}`);

            // 生成抢劫前的消息
            let preRobMsg = '';
            if (wealthGap > 1000) {
                preRobMsg = `你发现${targetNickname}非常富有，这是个很好的目标！`;
            } else if (wealthGap > 0) {
                preRobMsg = `${targetNickname}比你稍微富裕些，是个还不错的目标。`;
            } else {
                preRobMsg = `${targetNickname}比你还穷，可能不是个好目标...`;
            }

            // 如果目标有大量银行存款但现金不多，给出特殊提示
            if (targetBankBalance > targetCurrency * 3) {
                preRobMsg += `\n不过，${targetNickname}似乎把大部分财富都存入了银行，街头可抢的现金不多。`;
            }
            
            await e.reply([preRobMsg + "\n你悄悄靠近，准备下手..."]);
            
            // 延迟一会儿，增加紧张感
            await new Promise(resolve => setTimeout(resolve, 1500));

            // 决定抢劫是否成功
            if (Math.random() < finalRate) {
                // 抢劫成功：根据财富差距调整抢劫金额
                let baseRobRate = 0.2; // 基础抢劫比例
                let robRate = baseRobRate + (wealthRatio * 0.02); // 根据财富差距调整
                robRate = Math.min(Math.max(robRate, 0.1), 0.4); // 限制在10%-40%之间
                
                // 关键修改：只能从目标的余额中抢劫，不能从银行存款中抢劫
                const availableCash = targetCurrency; // 可抢劫的现金就是目标的余额
                const theoreticalRobAmount = formatCurrency(Math.min(availableCash * robRate, Math.max(100, availableCash * 0.3)));
                
                // 确保不会抢走对方全部现金
                const finalRobAmount = Math.min(theoreticalRobAmount, availableCash * 0.8);
                
                // 如果目标余额很少，可能抢到的金额也很少
                const actualRobAmount = Math.min(finalRobAmount, availableCash);
                
                userData.currency = formatCurrency(userData.currency + actualRobAmount);
                targetData.currency = formatCurrency(targetData.currency - actualRobAmount);
                
                // 根据抢劫金额和目标银行存款情况确定消息类型
                let robMsg = '';
                if (actualRobAmount > 500) {
                    robMsg = `抢劫大成功！你从${targetNickname}那里抢到了${actualRobAmount}金币，这是笔不小的财富！`;
                } else if (actualRobAmount > 200) {
                    robMsg = `抢劫成功！你从${targetNickname}那里抢到了${actualRobAmount}金币，收获颇丰。`;
                } else {
                    robMsg = `抢劫成功！你从${targetNickname}那里抢到了${actualRobAmount}金币。`;
                }
                
                // 如果目标的银行存款远高于现金，且抢到的很少，添加特殊消息
                if (targetBankBalance > targetCurrency * 2 && actualRobAmount < 100) {
                    robMsg += `\n可惜${targetNickname}把大部分财富都存在银行里了，你只能抢到这些零花钱...`;
                }
                
                // 劫富济贫的专属消息
                if (wealthGap > 1000 && actualRobAmount > 300) {
                    robMsg += `\n你成功地将一部分财富从富人那里重新分配到了自己口袋里！`;
                }
                
                await e.reply([robMsg]);
            } else {
                // 抢劫失败：根据财富差距调整惩罚金额
                const penaltyAmount = formatCurrency(Math.min(currency * finalPenalty, 50));
                userData.currency = formatCurrency(userData.currency - penaltyAmount);
                
                // 根据目标的财富生成不同的失败消息
                let failMsg = '';
                if (wealthGap > 1000) {
                    if (targetBankBalance > targetCurrency * 2) {
                        failMsg = `抢劫失败！${targetNickname}虽然很富有，但大部分钱都存在银行里。你因为精心策划却一无所获，被罚了${penaltyAmount}金币。`;
                    } else {
                        failMsg = `抢劫失败！${targetNickname}财大气粗，雇了保镖！你被罚了${penaltyAmount}金币。`;
                    }
                } else if (wealthGap > 0) {
                    failMsg = `抢劫失败！被${targetNickname}发现并报了警，你被罚了${penaltyAmount}金币。`;
                } else {
                    failMsg = `抢劫失败！${targetNickname}虽然穷，但身手不凡，你被罚了${penaltyAmount}金币。`;
                }
                
                await e.reply([failMsg]);
            }

            // 更新冷却时间
            userData.lastRobTime = currentSecond;
            
            // 保存数据
            storagePlayerData(ID[1], ID[0], userData);
            storagePlayerData(ID[1], targetId, targetData);
            
        } catch (error) {
            logger.error('处理抢劫请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }

    async resetrob(e) {
        if (!e.isMaster) return e.reply('只有主人才能重置冷却时间');
        if (!e.isGroup) return e.reply('该命令只能在群内使用');

        try {
            const groupId = e.group_id;
            const files = fs.readdirSync(`plugins/Slave-Market/data/player/${groupId}`);
            
            for (const file of files) {
                if (file.endsWith('.json')) {
                    const playerData = await getPlayerData(groupId, file.replace('.json', ''));
                    playerData.lastRobTime = 0;
                    storagePlayerData(groupId, file.replace('.json', ''), playerData);
                }
            }
            
            return e.reply('已重置本群所有成员的抢劫冷却时间');
        } catch (error) {
            logger.error('重置抢劫冷却时间时出错:', error);
            return e.reply('重置冷却时间时出错，请稍后再试');
        }
    }
}
